<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); 

class Cronjobs extends MY_Controller {
	
	protected $restricted = false;
	private $cronjob_conf;
	
	private $admin_email;
	private $admin_name;
	
	function Cronjobs() {
        parent::MY_Controller();

        
		$sql = "SELECT val FROM ".$this->tblc." WHERE name = ? LIMIT 1";
		$query = $this->db->query($sql, array("cronjobs"));
		$row = $query->row(); 	
		$this->cronjob_conf = json_decode($row->val);
		
 		$this->ci =& get_instance();

 		$this->admin_email = $this->ci->config->item('admin_email');
		$this->admin_name =  $this->ci->config->item('admin_name');
		
		
		if ($this->uri->segment(2) !== FALSE
           && ($this->uri->segment(3) === FALSE
           || $this->uri->segment(3) !== $this->cronjob_conf->key)) {
           redirect("cronjobs"); 
		}
        
        
	}

	function index() {
		$data['meta_title'] = "Cronjobs";
		$data['content'] = "<p>No cronjob selected or wrong/missing secret key.</p>";
		$this->load->view('cronjobs', $data);
	}
	
	
	function all($key) {
		$data['meta_title'] = "Cronjobs";
		$data['content'] = $this->_tippreminder($key);
		// $data['content'] .= ***WEITERE_CRONJOBS***
		$this->load->view('cronjobs', $data);
	}
	
	
	function tippreminder($key) {
		$data['meta_title'] = "Cronjobs";
		$data['content'] = $this->_tippreminder($key);
		$this->load->view('cronjobs', $data);
	}
	
	function mailedtipps($key) {
		$c['server'] = 'wp100.webpack.hosteurope.de:993';
		$c['login']  = 'wp1065621-tipp';
		$c['pass']   = 'p8RQkvHLrr9kjs';
		$c['service_flags'] = '/imap/ssl';
		$c['mailbox']= 'INBOX';
	}

	
	private function _tippreminder($key) {
		$hours = $this->cronjob_conf->tippreminder_hours;
		$last_id = $this->cronjob_conf->tippreminder_lastid;

		// Eine id eines Spiels, dass in den nächsten 24 Stunden startet
		$sql = "SELECT * FROM ".$this->tblm." as tblmatches"
				." WHERE tblmatches.deadline > now()"
				." AND DATE_SUB(tblmatches.deadline, INTERVAL ? HOUR) < now()"
				." ORDER BY tblmatches.deadline ASC, tblmatches.id ASC LIMIT 1";
		$query = $this->db->query($sql, array($hours));
		
		// Gibt es ein Spiel, dass in den nächsten hh Std. startet? 
		if ($query->num_rows() === 0) {
		 	$mes = "In den nächsten $hours Stunden startet kein Spiel.";
			$message = "<h2>Cronjob - tippreminder</h2>".$mes;
			return $message;
		}
		
		$res = $query->result();
		$nextGame = $res[0];

		$str_date  = date("d.m.Y H:i", strtotime($nextGame->deadline));
 		$str_match = $nextGame->team_h." - ".$nextGame->team_a;
		
		// Wurde für dieses Spiel schon eine Email geschickt?
		if ($last_id == $nextGame->id) {
		 	$mes = "Für das Spiel <strong>$str_match</strong> wurde schon eine Email verschickt.";
			$message = "<h2>Cronjob - tippreminder</h2>".$mes;
			return $message;
		}

		// Text für die Email erstellen
		$email_text = "Noch nicht getippt!\n";
		$email_text .= "Das folgende Spiel startet innerhalb der nächsten $hours Stunden.\n\n";
		$email_text .= "$str_match ($str_date)\n\n";
		$email_text .= $this->ci->config->item('base_url')."matches\n\n";
		$email_text .= "Viel Erfolg beim Tippen.";
		
		// Alle Tipper, die dieses Spiel noch nicht getippt haben	
		$sql = "SELECT "
					."tblu.name AS name,"
					."tblu.email AS email,"
					."tblu.settings AS settings"
				." FROM ".$this->tblu." as tblu"
				." LEFT JOIN ".$this->tblt." AS tblt ON ( tblu.id = tblt.user_id"
				." AND tblt.match_id = ?)"
 				." WHERE tblt.tipp_id IS NULL ORDER BY name";

 		$query = $this->db->query($sql, array($nextGame->id));

 		
 		$mes = "<pre>$email_text</pre>\n";
 		$mes .= "<ol>\n";
 		$userArr = array();

 		// Email an die Benutzer schicken
 		foreach($query->result() as $user) {
 			$userArr[] = "  * ".$user->name." (".$user->email.")";
 			$mes .= $this->_mailNotTipped($email_text, $user); 
 		}
 		$mes .= "</ol>\n";
 		
 		// Email an Admin
 		$subject = "Tipperinnerung - Emails verschickt";
 		$admin_mes  = "Es wurden Emails an folgende Tipper geschickt:\n\n"; 
 		$admin_mes .= implode("\n", $userArr)."\n\n";
 		$admin_mes .= "Tippmaster";
 		$this->_mailToAdmin($subject, $admin_mes);
 		
 		
 		// Speichern dass für das Spiel eine Mail geschickt wurde
 		$this->cronjob_conf->tippreminder_lastid = $nextGame->id;
		$value = json_encode($this->cronjob_conf);
 		$sql = "UPDATE ".$this->tblc." SET val = ? WHERE name = ?";
		$query = $this->db->query($sql, array ($value, "cronjobs"));

		$message = "<h2>Cronjob - tippreminder</h2>".$mes;
		return $message;
	}

	
	private function _mailToAdmin($subject, $message) {

		$this->email->from($this->admin_email, $this->admin_name);
		$this->email->to($this->admin_email);

		$this->email->subject($subject);
		$this->email->message($message);
		$this->email->send();
	}
	
	
	
	private function _mailNotTipped($mes, $user) {
  	
    	$subject = "Tipperinnerung";
    	$message = $mes;

    	$this->email->from($this->admin_email, $this->admin_name);
		$this->email->to($user->email);

		$this->email->subject($subject);
		$this->email->message($message);
		$this->email->send();

		return "	<li>".$user->name." - ".$user->email."</li>\n";
	}
	

}
